
// Table B1 and C1

/* =============================================================================
   Step 1: Data processing
   ===========================================================================*/
* Loading BSU link to BSU number in 2014
use "${datain}grk_link_to_grk_number_in_2014", clear 
duplicates drop grk, force
tempfile grklink 
save `grklink', replace

* Loading congestion data for Oslo and Viken from database file 
import dbase using "${datain}losdata_viken" , clear
drop if TID_MRUSH == 0
drop if TID_MRUSH == .
* Averaging morning and afternoon rush
gen TID_RUSH = (TID_MRUSH + TID_ERUSH) / 2

* Measure of congestion: Relative increase in driving time in rush vs outside rush
gen congestion = (TID_RUSH-TID_LAV)/TID_LAV
rename FRA from // Basic statistical unit (grunnkrets) for origin
rename TIL to // Basic statistical unit (grunnkrets) for destination
keep from to congestion
duplicates drop from to, force

* Adding the 2014 BSU numbers to origin BSU
gen grk = from 
merge m:1 grk using `grklink', keep(match master)
drop _merge grk
rename grk2014 from2014 
* Adding the 2014 BSU numbers to destination BSU
gen grk = to 
merge m:1 grk using `grklink', keep(match master)
drop _merge grk
rename grk2014 to2014 

* In case the BSU numbers for 2014 are missing, use existing number
* This is the case for all BSUs that have not changed number over time
replace from = from2014 if from2014 != . 
replace to = to2014 if to2014 != .
drop from2014 to2014
duplicates drop from to, force

* Store dataset
tempfile congestion 
save `congestion', replace

* === Go to main data ==========================================================
use "${dataout}MainDataset" , clear

keep if year >= 2015 & year <= 2017

gen from = grkrets_num 
gen to = grk_bed1_num 

* merging congestion to work for person 1
merge m:1 from to using `congestion', keep(match master)
drop _merge 
rename congestion congestion_to1

rename from temp 
rename to from 
rename temp to 

* merging congestion from work for person 1
merge m:1 from to using `congestion', keep(match master)
drop _merge 
rename congestion congestion_from1

drop from to

gen from = grkrets_num 
gen to = grk_bed2_num 

* merging congestion to work for person 2
merge m:1 from to using `congestion', keep(match master)
drop _merge 
rename congestion congestion_to2

rename from temp 
rename to from 
rename temp to 

* merging congestion from work for person 2
merge m:1 from to using `congestion', keep(match master)
drop _merge 
rename congestion congestion_from2
drop from to

* For each household member ...
forvalues i = 1/2 {
	/* Average of to/from work */
	gen congestion`i' = (congestion_from`i' + congestion_to`i') / 2
	// if congestion_to is missing, use congestion_from as proxy
	replace congestion`i' = congestion_from`i' if congestion`i' == .
	// if congestion_from is missing, use congestion_to as proxy
	replace congestion`i' = congestion_to`i' if congestion`i' == .
}

/* Average value across household members */
egen congestion = rowmean(congestion1 congestion2)

/* Sample selection for regressions */
keep if congestion != . /* Oslo and Viken */
keep if couple == 1 /* only couples */

/* =============================================================================
   Step 2: Run regressions - all outcomes except BEV
   ===========================================================================*/

local outcomelist car_fam_count car_fam_yes ICE_fam_count 
local treatvar1list toll_fam_mean      
local treatvar2list ptl_fam_km_mean     
* Couples

** Regressions - loop over: outcome, treatment, year
foreach outcome in `outcomelist'{
	foreach treatvar1 in `treatvar1list'{
		foreach treatvar2 in `treatvar2list'{
			* Run regression where we control for congestion
			reghdfe `outcome' `treatvar1'  `treatvar2' congestion ///
			$age $distance $time $publictime $publicquality if couple == 1  , ///
			absorb($FE   $household  $income  $employment  $education  i.year) /// 
			vce(cluster $clustervar) 
			
			* Adding regression results
			summarize congestion if e(sample)==1
			estadd scalar MeanCong = r(mean), replace
			summarize `outcome' if e(sample)==1
			estadd scalar MeanDep = r(mean), replace
			summarize `treatvar1' if e(sample)==1
			estadd scalar Treat1 = r(mean), replace
			summarize `treatvar2' if e(sample)==1
			estadd scalar Treat2 = r(mean), replace
			estadd local year="2015-17" , replace
			estadd local cong="\checkmark", replace
			estadd local grkFE="\checkmark", replace
			estadd local grkbFE="\checkmark", replace
			estadd local HHcon="\checkmark", replace
			estadd local HHWork="\checkmark", replace
			estadd local PublicTime="\checkmark", replace
			estadd local grkFE_W="Yes", replace
			estadd local grkbFE_W="Yes", replace
			estadd local HHcon_W="Yes", replace
			estadd local HHWork_W="Yes", replace
			estadd local PublicTime_W="Yes", replace
			eststo cong2_`outcome' 

			* For saving the estimates as ster files with the right name 
			local savefig = "`outcome'"
			if "`savefig'" == "car_fam_count" {
				estimates save "${ster}TableB1reg2", replace
			} 
			if "`savefig'" == "car_fam_yes" {
				estimates save "${ster}TableB1reg4", replace
			}
			if "`savefig'" == "ICE_fam_count" {
				estimates save "${ster}TableC1reg4", replace
			}
			
			* Marking estimation sample
			capt drop MainSample
			gen MainSample=0
			replace MainSample=1 if e(sample)==1
			
			* Run regression without congestion
			reghdfe `outcome' `treatvar1'  `treatvar2'  $age    $distance  $time  $publictime  $publicquality if couple == 1 & MainSample == 1 , ///
			absorb($FE   $household  $income  $employment  $education  i.year   ) vce(cluster $clustervar) 
			summarize `outcome' if e(sample)==1
			estadd scalar MeanDep = r(mean), replace
			summarize `treatvar1' if e(sample)==1
			estadd scalar Treat1 = r(mean), replace
			summarize `treatvar2' if e(sample)==1
			estadd scalar Treat2 = r(mean), replace
			estadd local year="2015-17" , replace
			estadd local cong="", replace
			estadd local grkFE="\checkmark", replace
			estadd local grkbFE="\checkmark", replace
			estadd local HHcon="\checkmark", replace
			estadd local HHWork="\checkmark", replace
			estadd local PublicTime="\checkmark", replace
			estadd local grkFE_W="Yes", replace
			estadd local grkbFE_W="Yes", replace
			estadd local HHcon_W="Yes", replace
			estadd local HHWork_W="Yes", replace
			estadd local PublicTime_W="Yes", replace
			eststo cong1_`outcome'
			
			* For saving the estimates as ster files with the right name 
			local savefig = "`outcome'"
			if "`savefig'" == "car_fam_count" {
				estimates save "${ster}TableB1reg1", replace
			} 
			if "`savefig'" == "car_fam_yes" {
				estimates save "${ster}TableB1reg3", replace
			}
			if "`savefig'" == "ICE_fam_count" {
				estimates save "${ster}TableC1reg3", replace
			}
		}
	}
}

/* =============================================================================
   Step 3: Run BEV regressions
   ===========================================================================*/
   
* storing the true value of the variables
gen ptl_fam_km_mean_true = ptl_fam_km_mean
gen congestion_true = congestion

* demeaned variables - for interaction effects
sum ptl_fam_km_mean if MainSample == 1  
replace ptl_fam_km_mean  = ptl_fam_km_mean  - r(mean)
sum congestion if MainSample == 1
replace congestion = congestion - r(mean)

* Run regression with controls for congestion incl interaction with bus lane
reghdfe BEV_fam_yes toll_fam_mean  ptl_fam_km_mean ///
congestion c.congestion#c.ptl_fam_km_mean ///
$age $distance $time $publictime $publicquality if couple == 1  , ///
absorb($FE   $household  $income  $employment  $education  i.year) /// 
vce(cluster $clustervar) 

summarize congestion_true if e(sample)==1
estadd scalar MeanCong = r(mean), replace
summarize BEV_fam_yes if e(sample)==1
estadd scalar MeanDep = r(mean), replace
summarize toll_fam_mean if e(sample)==1
estadd scalar Treat1 = r(mean), replace
summarize ptl_fam_km_mean_true if e(sample)==1
estadd scalar Treat2 = r(mean), replace
estadd local year="2015-17" , replace
estadd local cong="\checkmark", replace
estadd local grkFE="\checkmark", replace
estadd local grkbFE="\checkmark", replace
estadd local HHcon="\checkmark", replace
estadd local HHWork="\checkmark", replace
estadd local PublicTime="\checkmark", replace
estadd local grkFE_W="Yes", replace
estadd local grkbFE_W="Yes", replace
estadd local HHcon_W="Yes", replace
estadd local HHWork_W="Yes", replace
estadd local PublicTime_W="Yes", replace
eststo cong2_BEV_fam_yes

* Save results to ster
estimates save "${ster}TableC1reg2", replace

* Mark estimation sample
capt drop MainSample
gen MainSample=0
replace MainSample=1 if e(sample)==1
			
* Back to original values
replace ptl_fam_km_mean = ptl_fam_km_mean_true

* Run BEV regression without congestion 
reghdfe BEV_fam_yes toll_fam_mean  ptl_fam_km_mean ///
$age $distance $time $publictime $publicquality if couple == 1 & MainSample == 1 , ///
absorb($FE $household $income $employment $education i.year) ///
vce(cluster $clustervar) 

summarize BEV_fam_yes if e(sample)==1
estadd scalar MeanDep = r(mean), replace
summarize toll_fam_mean if e(sample)==1
estadd scalar Treat1 = r(mean), replace
summarize ptl_fam_km_mean if e(sample)==1
estadd scalar Treat2 = r(mean), replace
estadd local year="2015-17" , replace
estadd local cong="", replace
estadd local grkFE="\checkmark", replace
estadd local grkbFE="\checkmark", replace
estadd local HHcon="\checkmark", replace
estadd local HHWork="\checkmark", replace
estadd local PublicTime="\checkmark", replace
estadd local grkFE_W="Yes", replace
estadd local grkbFE_W="Yes", replace
estadd local HHcon_W="Yes", replace
estadd local HHWork_W="Yes", replace
estadd local PublicTime_W="Yes", replace
eststo cong1_BEV_fam_yes

* Save results to ster
estimates save "${ster}TableC1reg1", replace

/* =============================================================================
   Step 4: Create table B.1 from saved .ster files
   ===========================================================================*/

* Retrieving estimates   
eststo drop *
estimates use "${ster}TableB1reg1"  
eststo
estimates use "${ster}TableB1reg2"    
eststo
estimates use "${ster}TableB1reg3"    
eststo
estimates use "${ster}TableB1reg4"   
eststo

* Exporting table
esttab est*  ///
	using  "${tables}TableB1.tex" ///
	, keep(toll_fam_mean  ptl_fam_km_mean) ///
	coeflabels( ///
			toll_fam_mean "Road toll (NOK)" ///
			ptl_fam_km_mean "Bus lane (km)" ///
		) ///	
	title("Robustness, congestion. Year: 2015-2017") ///
	mgroups("Cars" "Car (yes = 1)", pattern(1 0 1 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat (\cmidrule(lr){@span}) ) ///
	booktabs nonotes nomtitle /// 
	stats(year N  cong grkFE grkbFE HHWork HHcon PublicTime MeanDep Treat1 Treat2 , ///
		label("Year" "N" "Congestion" "Neighborhood FE" "Neighborhood work FE"  "Ind-work controls" "HH and ind controls"  "Public transit (minutes)"  "Mean of dep.var" "Mean road toll (NOK)" "Mean bus lane (km)")) ///
	se star(* 0.10 ** 0.05 *** 0.01) replace substitute (\_ _)	
    
/* =============================================================================
   Step 5: Create table C.1 from saved .ster files
   ===========================================================================*/

* Retrieving estimates
eststo drop *
estimates use "${ster}TableC1reg1"  
eststo
estimates use "${ster}TableC1reg2"    
eststo
estimates use "${ster}TableC1reg3"    
eststo
estimates use "${ster}TableC1reg4"   
eststo

* Exporting table
esttab est*  ///
	using  "${tables}TableC1.tex" ///
	, keep(toll_fam_mean  ptl_fam_km_mean congestion c.congestion#c.ptl_fam_km_mean ) ///
	coeflabels( ///
			toll_fam_mean "Road toll (NOK)" ///
			ptl_fam_km_mean "Bus lane (km)" ///
			congestion "Congestion" ///
			c.congestion#c.ptl_fam_km_mean "Congestion $\times$ Bus lane" ///
		) ///	
	title("Robustness, congestion. Year: 2015-2017") ///
	mgroups("BEV (yes = 1)" "ICEVs", pattern(1 0 1 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat (\cmidrule(lr){@span}) ) ///
	booktabs nonotes nomtitle /// 
	stats(year N  cong grkFE grkbFE HHWork HHcon PublicTime MeanDep Treat1 Treat2 MeanCong, ///
		label("Year" "N" "Congestion" "Neighborhood FE" "Neighborhood work FE"  "Ind-work controls" "HH and ind controls"  "Public transit (minutes)"  "Mean of dep.var" "Mean road toll (NOK)" "Mean bus lane (km)" "Mean congestion")) ///
	se star(* 0.10 ** 0.05 *** 0.01) replace substitute (\_ _)	   
   
